//
//  ZZXuserNotesLikeViewController.m
//  Travel
//
//  Created by dllo on 15/12/1.
//  Copyright © 2015年 doll. All rights reserved.
//

#import "ZZXuserNotesLikeViewController.h"
#import "KHHRecommendIndexViewCell.h"
#import "KHHTravelNotesDetailPageViewController.h"
#import "Story.h"
#import "CoreDataManager.h"

@interface ZZXuserNotesLikeViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *dataArr;
@property (nonatomic, strong)NSMutableArray *dataArr2;
@property (nonatomic, strong)UILabel *label;
@property (nonatomic, retain) CoreDataManager *manager;
@property (nonatomic, retain) NSMutableArray *arr_result;

@end


@implementation ZZXuserNotesLikeViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"fanhui"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(backToLast)];
    //初始化coredata单例
    self.manager = [CoreDataManager shareInstance];
    
    [self getData];
}

#pragma mark - 视图将要出现
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear: animated];
    
//    if ([[NSUserDefaults standardUserDefaults]boolForKey:@"isNight"])
//    {
//        self.tableView.backgroundColor = [UIColor colorWithRed:0.28 green:0.28 blue:0.28 alpha:1];
//        self.view.backgroundColor = [UIColor colorWithRed:0.28 green:0.28 blue:0.28 alpha:1];
//    } else {
//        self.tableView.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
//        self.view.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.94 alpha:1];
//    }
    
    [self selectAllLike];
    
    [self.tableView reloadData];
    
}

//查询数据库
- (void)selectAllLike
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Trave" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    
    //*******谓词 /过滤数据 (注掉就查询所有)******
    //准确查询
    
    // NSPredicate *predicate = [NSPredicate predicateWithFormat:@"index_title = %@", self.recommendModel.index_title];
    
    //[fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    
    //排序 参数:根据什么排序 yes 升序  / no 降序
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"avatar_m"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        
    }
    [self.arr_result removeAllObjects];
    self.arr_result = [NSMutableArray arrayWithArray:fetchedObjects];
    
    [self.tableView reloadData];
}

- (void)createTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    
    self.tableView.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.94 alpha:1];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
//    [self MJRefresh];

}

//- (void)MJRefresh
//{
//    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        [self getData];
//        
//        [self.tableView.header endRefreshing];
//    }];
//}

#pragma mark - 按钮触发方法
- (void)backToLast
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)getData
{
//    //路径
//    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"notesLike.plist"];
//    
//    //路径
//    NSString *path2 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"notesUserLike.plist"];
//    //先解档 从本地获取一个数组 如果没有值 则新建空数组 如果有值 将当前对象添加进数组
//    self.dataArr  = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
//    self.dataArr2 = [NSKeyedUnarchiver unarchiveObjectWithFile:path2];
//    
    [self selectAllLike];
    
    if (self.tableView != nil) {
        [self.tableView reloadData];
        
    } else {
        [self createTableView];
        
    }
    
    if (self.arr_result.count == 0) {
        if (!self.label) {
            self.label = [[UILabel alloc]initWithFrame:CGRectMake(CWIDTH / 2 - 40 , CHEIGHT / 2 - 40, CWIDTH - 40, 60)];
            self.label.text = @"暂无收藏";
            //  self.label.center = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2);
            [self.view addSubview:self.label];
        }
    }
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arr_result.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    KHHRecommendIndexViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[KHHRecommendIndexViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    cell.travelModel = self.arr_result[indexPath.row];
    cell.travelUserModel = self.arr_result[indexPath.row];
    
    return cell;
    
}

#pragma mark - tableView 点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    KHHTravelNotesDetailPageViewController *notes = [[KHHTravelNotesDetailPageViewController alloc]init];
    
    
    //推荐页收藏时 点击详情页传了id 和对象  要想在收藏页取消收藏  也要传递过去对象  才能在likeTool里判断是否收藏过
    notes.recommendModel = self.arr_result[indexPath.row];
    notes.recommentUserModel = self.arr_result[indexPath.row];
    
    notes.locationImpressionToDetailID = [self.arr_result[indexPath.row] valueId];
    [self.navigationController pushViewController:notes animated:YES];
    
}

#pragma mark - 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
   KHHRecommendModel *tempModel = self.arr_result[indexPath.row];
    
    
    //自适应标题
    CGFloat HTitleLable = [[self class]heightWithText:tempModel.name fontSize:18 Width:CWIDTH - 40];
    
    return    5 + 10 + HTitleLable + 10 + 15 + 5 + 15 + 200 / 4 + 10 + 10 + (WIDTH - 20) / 6;
    
}
#pragma mark-滑动手势1
- (void)addScreenEdgePan
{
    UIScreenEdgePanGestureRecognizer *screenEdgePan = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(presentLeftMenuViewController:)];
    screenEdgePan.edges = UIRectEdgeLeft;
    [self.view addGestureRecognizer:screenEdgePan];
    [self.tableView addGestureRecognizer:screenEdgePan];
   
}
#pragma mark-滑动手势2
-(void)presentLeftMenuViewController:(UIScreenEdgePanGestureRecognizer *)edge
{
    [self.navigationController popViewControllerAnimated:YES];
}

    
    
    
    
    


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
